package com.spring.mvc.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
/*
 * 文件上传
 */
@Controller
public class UploadController {	
	/**
	 * 
	 * @param name 名字
	 * @param file 文件
	 * @return
	 */
	@RequestMapping(value="/upload.action",method=RequestMethod.POST)
	public ModelAndView upload(@RequestParam("name") String name,@RequestParam("file") MultipartFile file) {				
		//新文件名
        String newFileName = UUID.randomUUID()+name;
		//上传到什么地方
        String path = "g:/upload/";
        File f = new File(path);
        if(!f.exists())f.mkdirs();
		if (!file.isEmpty()) {
			System.out.println(name + ":" + file.getSize());
			  try {
	                FileOutputStream fos = new FileOutputStream(path+newFileName);
	                InputStream in = file.getInputStream();
	                int b = 0;
	                while((b=in.read())!=-1){
	                    fos.write(b);
	                }
	                fos.close();
	                in.close();
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
		}
		ModelAndView mv = new ModelAndView();
		mv.setViewName("upload");
		return mv;
	}
	/**
	 * spring的上传
	 * @throws  
	 * 
	 * 
	 */
	@RequestMapping(value="/upload1.action",method=RequestMethod.POST)
	public String UploadFile(@RequestParam("file1") MultipartFile file1 ,HttpServletRequest request ) throws Exception{
		/*
		 * 注意：request.getServletContext() 要javax.servlet-api jar 版本要3.0
		 */
		String filePath=request.getServletContext().getRealPath("/");
		file1.transferTo(new File(filePath+"upload/"+file1.getOriginalFilename()));
		return "success";	
	}
	/*
	 * spring mvc 多文件上传
	 * 
	 */
	@RequestMapping("/upload2.action")
	public String uploadFiles(@RequestParam("file2") MultipartFile[] files,HttpServletRequest request)throws Exception{
		String filePath=request.getSession().getServletContext().getRealPath("/");
		System.out.println(filePath);
		for(MultipartFile file2:files){
			file2.transferTo(new File(filePath+"upload/"+file2.getOriginalFilename()));			
		}
		return "success";
	}
}
